﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;
using System.Xml;
using log4net;
using log4net.Config;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Office = Microsoft.Office.Core;
using Microsoft.Win32;

namespace BPVote
{
    public partial class ThisAddIn
    {
        // 文件的目录
        private const string BPVoteInstallPath = @"BPVote Add-in for Word";
        private static readonly ILog logger = LogManager.GetLogger(typeof(ThisAddIn));

        //注册表中的位置
        private static readonly string AddInRegistryKeyPath = "";
        private static readonly string AddInManifestKeyName = @"Manifest";

        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            SetUpLogging();
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
        }

        protected override object RequestService(Guid serviceGuid)
        {
            //
            return base.RequestService(serviceGuid);
        }

        /// <summary>
        /// 取得程序集的位置
        /// </summary>
        /// <returns></returns>
        private static string GetAssemblyDirectoryName()
        {
            string addInInstallPath = String.Empty;

            RegistryKey addInKey = addInKey = Registry.CurrentUser.OpenSubKey(AddInRegistryKeyPath, false);

            if (addInKey == null)
            {
                addInKey = Registry.LocalMachine.OpenSubKey(AddInRegistryKeyPath, false);
            }

            using (addInKey)
            {
                if (addInKey != null)
                {
                    var registryValue = addInKey.GetValue(AddInManifestKeyName);

                    if (registryValue != null)
                    {
                        var registryPath = registryValue.ToString();

                        int invalidCharPosition = registryPath.IndexOfAny(Path.GetInvalidPathChars());
                        while (invalidCharPosition > -1)
                        {
                            registryPath = registryPath.Remove(invalidCharPosition, 1);
                            invalidCharPosition = registryPath.IndexOfAny(Path.GetInvalidPathChars());
                        }

                        addInInstallPath = Path.GetDirectoryName(registryPath);
                    }
                }
            }

            return addInInstallPath;
        }

        /// <summary>
        /// 设置日志信息
        /// </summary>
        private static void SetUpLogging()
        {
            string appDataFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), BPVoteInstallPath);
            string configFilePath = Path.Combine(appDataFolder, "Log4NetConfig.xml");
            
            if (File.Exists(configFilePath))
            {
                try
                {
                    File.SetAttributes(configFilePath, FileAttributes.Normal);
                }
                catch (Exception)
                {
                    logger.Debug("Failed to configure logging!");
                }
            }
            FileInfo configFile = new FileInfo(configFilePath);
            if (!configFile.Exists)
            {
                string addInstallPath = GetAssemblyDirectoryName();
                string logPath = Path.Combine(addInstallPath, "Log4NetConfig.xml");
                if (File.Exists(logPath))
                {
                    File.Copy(logPath, configFile.FullName);
                    XmlDocument document = new XmlDocument();
                    document.Load(configFile.FullName);

                    foreach (XmlNode node in document.GetElementsByTagName("file"))
                    {
                        node.Attributes.GetNamedItem("value").Value = Path.Combine(appDataFolder, "BPVote.log");
                        break;
                    }
                }
                else
                {
                    throw new Exception("Could not find logging configuration file.");
                }
            }
            XmlConfigurator.Configure(configFile);
        }
        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }
        
        #endregion
    }
}
